import { Dispatch, useReducer } from "react";

// Define reducer state structure
export type PersonState = {
    name: string;
    loading: boolean;
    group: string[];
    age: number;
}

// define actions eumn
export enum PsersonActionType {
    INIT_LOAD,
    SET_LOADING,
    SET_NAME,
    SET_GROUP,
    SET_AGE
}

// define specific action type: use below in specific function to update
export type InitLoad = {
    type: PsersonActionType.INIT_LOAD;
    value: PersonState;
}

export type SetLoading = {
    type: PsersonActionType.SET_LOADING;
    value: boolean;
}

export type SetName = {
    type: PsersonActionType.SET_NAME;
    value: string;
}

export type SetAge = {
    type: PsersonActionType.SET_AGE;
    value: number;
}

export type SetGroup = {
    type: PsersonActionType.SET_GROUP;
    value: string[];
}

// define actions, combine all action type to entire one.  Use it in parameters places
export type PersonActions = InitLoad | SetLoading | SetName | SetAge | SetGroup;


// Initialize state
const getPersonInitState = (): PersonState => {
    return {
        name: '',
        loading: false,
        group: [],
        age: 0
    };
};


// reducer logic: two parameters: state interface and actions
const personReducer = (
    state: PersonState, action: PersonActions
): PersonState => {
    switch (action.type) {
        case PsersonActionType.INIT_LOAD:
            return action.value;
        case PsersonActionType.SET_LOADING:
            return {
                ...state,
                loading: action.value
            };
        case PsersonActionType.SET_NAME:
            return {
                ...state,
                name: action.value
            };
        case PsersonActionType.SET_AGE:
            return {
                ...state,
                age: action.value
            };
        case PsersonActionType.SET_GROUP:
            return {
                ...state,
                group: action.value
            };
        default:
            return state;
    }
};

// create reducer with useReducer
export const usePersonReducer = () : [ PersonState,Dispatch<PersonActions>] => useReducer(personReducer, getPersonInitState());
